local Upload = require("luv-http.upload")

local M = {}
M.new = function (ctx, initParam)
    local handler = function (req, resp, ctx)
        local body = "not multipart/form-data request"
        local isMultipart, extractor = Upload.checkMultipart(req, function (name, value, isText, headers)
            if isText then
                body = body .. "isText:" .. tostring(isText) .. "," .. name .. ":" .. value .. "<br>"
            else
                if value.blob then
                    body = body .. "isText:" .. tostring(isText) .. "," .. name .. ":" .. value.value .. ":" .. value.contentType .. ":" .. value.blob.path .. "<br>"
                else
                    body = body .. "isText:" .. tostring(isText) .. "," .. name .. ":" .. value.value .. "<br>"
                end
            end
        end, Upload.getFileStoreEngine(ctx.envCfg.tmpDir))
        if isMultipart then
            body = ""
            local thread = coroutine.running()
            req:on("data", extractor)
            req:on("end", function()
                coroutine.resume(thread)
            end)
            coroutine.yield()
        end
        resp.statusCode = 200
        resp:setHeader("Content-Type", "text/html")
        resp:setHeader("Content-Length", string.len(body))
        resp:write(body)
    end
    return handler
end

local moduleName = ...
_G[moduleName] = M
complex = M
return complex